package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.TEMPLATE_SYS;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jspgou.cms.Constants;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.tpl.Tpl;
import com.jspgou.core.tpl.TplManager;

@Controller
public class TemplateFroAct {	
	private static final Logger log = LoggerFactory.getLogger(TemplateFroAct.class);
	
	/**
	 * 店铺模板页
	 */
	public static final String STORE_TEMPLATE_MAIN= "tpl.storeTemplateMain";
	/**
	 * 店铺模板左侧页
	 */
	public static final String STORE_TEMPLATE_LEFT= "tpl.storeTemplateLeft";
	/**
	 * 店铺模板树页
	 */
	public static final String STORE_TEMPLATE_TREE= "tpl.storeTemplateTree";
	/**
	 * 店铺模板列表页
	 */
	public static final String STORE_TEMPLATE_LIST= "tpl.storeTemplateList";
	/**
	 * 店铺模板重命名页
	 */
	public static final String STORE_TEMPLATE_RENAME= "tpl.storeTemplateRename";
	/**
	 * 店铺模板添加页
	 */
	public static final String STORE_TEMPLATE_ADD= "tpl.storeTemplateAdd";
	/**
	 * 店铺模板修改页
	 */
	public static final String STORE_TEMPLATE_EDIT= "tpl.storeTemplateEdit";
	
	@RequestMapping(value = "/template/main.jspx")
	public String main(String cl,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		model.addAttribute("cl", cl);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_MAIN), request);
	}
	
	@RequestMapping(value = "/template/left.jspx")
	public String left(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_LEFT), request);
	}
	
	@RequestMapping(value = "/template/tree.jspx")
	public String tree(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		String root = RequestUtils.getQueryParam(request, "root");
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		log.debug("tree path={}", root);
		boolean isRoot;
		String equipment=(String)request.getAttribute("ua");
		// jquery treeview的根请求为root=source
		if (StringUtils.isBlank(root) || "source".equals(root)) {
			//移动端入口
			if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
				root = "/WEB-INF/t/store/mobile_u/"+store.getStorePath();
			}else{
				//pc端入口
				root = "/WEB-INF/t/store/u/"+store.getStorePath();
			}
			isRoot = true;
		} else {
			isRoot = false;
		}
		model.addAttribute("isRoot", isRoot);
		List<? extends Tpl> tplList = tplManager.getChild(root);
		model.addAttribute("tplList", tplList);
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_TREE), request);
	}
	
	@RequestMapping(value = "/template/list.jspx")
	public String list(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = (String) model.get("roott");
		if (roott == null) {
			roott = RequestUtils.getQueryParam(request, "roott");
		}
		log.debug("list Template roott: {}", roott);
		String equipment=(String)request.getAttribute("ua");
		if (StringUtils.isBlank(roott)) {
			//移动端入口
			if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
				roott = "/WEB-INF/t/store/mobile_u/"+store.getStorePath();
			}else{
				//pc端入口
				roott = "/WEB-INF/t/store/u/"+store.getStorePath();
			}
		}
//		String rel = root.substring(site.getTplPath().length());
//		if (rel.length() == 0) {
//			rel = "/";
//		}
		model.addAttribute("roott", roott);
//		model.addAttribute("rel", rel);
		model.addAttribute("list", tplManager.getChild(roott));
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_LIST), request);
	}
	
	@RequestMapping(value = "/template/rename.jspx", method = RequestMethod.GET)
	public String rename(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return "redirect:../login.jspx";
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = RequestUtils.getQueryParam(request, "roott");
		String name = RequestUtils.getQueryParam(request, "name");
		String equipment=(String)request.getAttribute("ua");
		String path=null;
		//移动端入口
		if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
			path="/WEB-INF/t/store/mobile_u/"+store.getStorePath();
		}else{
			path="/WEB-INF/t/store/u/"+store.getStorePath();
		}
		String origName = name.substring(path.length());
		model.addAttribute("origName", origName);
		model.addAttribute("roott", roott);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_RENAME), request);
	}
	
	@RequestMapping(value = "/template/o_rename.jspx", method = RequestMethod.POST)
	public String saveRename(String roott, String origName, String distName,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String equipment=(String)request.getAttribute("ua");
		String path=null;
		if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
			path="/WEB-INF/t/store/mobile_u/"+store.getStorePath();
		}else{
			path="/WEB-INF/t/store/u/"+store.getStorePath();
		}
		String orig = path + origName;
		String dist = path + distName;
		tplManager.rename(orig, dist);
		log.info("name Template from {} to {}", orig, dist);
		model.addAttribute("roott", roott);
		return list(request, model);
	}
	
	@RequestMapping(value = "/template/add.jspx", method = RequestMethod.GET)
	public String add(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = RequestUtils.getQueryParam(request, "roott");
		model.addAttribute("roott", roott);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_ADD), request);
	}
	
	@RequestMapping("/template/save.jspx")
	public String save(String roott, String filename, String source,
			HttpServletRequest request, ModelMap model) {
		String name = roott + "/" + filename + Constants.TPL_SUFFIX;
		tplManager.save(name, source, false);
		model.addAttribute("roott", roott);
		log.info("save Template name={}", filename);
		return list(request, model);
	}
	
	@RequestMapping("/template/edit.jspx")
	public String edit(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = RequestUtils.getQueryParam(request, "roott");
		String name = RequestUtils.getQueryParam(request, "name");
		model.addAttribute("template", tplManager.get(name));
		model.addAttribute("roott", roott);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(TEMPLATE_SYS, MessageResolver.getMessage(request,STORE_TEMPLATE_EDIT), request);
	}
	
	// AJAX请求，不返回页面
	@RequestMapping("/template/o_update.jspx")
	public void update(String roott, String name, String source,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		tplManager.update(name, source);
		log.info("update Template name={}.", name);
		model.addAttribute("roott", roott);
		ResponseUtils.renderJson(response, "{success:true}");
	}
	
	@RequestMapping("/template/o_delete.jspx")
	public String delete(String roott, String[] names,
			HttpServletRequest request, ModelMap model) {
		int count = tplManager.delete(names);
		log.info("delete Template count: {}", count);
		model.addAttribute("roott", roott);
		return list(request, model);
	}
	
	@RequestMapping("/template/o_delete_single.jspx")
	public String deleteSingle(HttpServletRequest request, ModelMap model) {
		String roott = RequestUtils.getQueryParam(request, "roott");
		String name = RequestUtils.getQueryParam(request, "name");
		int count = tplManager.delete(new String[] { name });
		model.addAttribute("roott", roott);
		return list(request, model);
	}
	
	@RequestMapping(value = "/template/o_swfupload.jspx", method = RequestMethod.POST)
	public void swfUpload(
			String roott,
			@RequestParam(value = "Filedata", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws IllegalStateException, IOException {
		tplManager.save(roott, file);
		model.addAttribute("roott", roott);
		log.info("file upload seccess: {}, size:{}.", file
				.getOriginalFilename(), file.getSize());
		ResponseUtils.renderText(response, "");
	}
	
	@RequestMapping(value = "/template/o_create_dir.jspx")
	public String createDir(String roott, String dirName,
			HttpServletRequest request, ModelMap model) {
		// TODO 检查dirName是否存在
		tplManager.save(roott + "/" + dirName, null, true);
		model.addAttribute("roott", roott);
		return list(request, model);
	}
	
	private TplManager tplManager;
	
	public void setTplManager(TplManager tplManager) {
		this.tplManager = tplManager;
	}
}
